package logic

import (
	"context"
	"fmt"
	"huiyun/model/cache"
	"huiyun/model/mysql"

	"huiyun/huiyunrpc/huiyunrpc"
	"huiyun/huiyunrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登陆
func (l *LoginLogic) Login(in *huiyunrpc.LoginRequest) (*huiyunrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var finduser mysql.User
	mysql.DB.Debug().Where("phone=?", in.Phone).Find(&finduser)
	result, _ := cache.Rdb.Get(l.ctx, "senSms"+in.Phone).Result()
	if result != in.SendCode {
		return nil, fmt.Errorf("该短信验证码错误,请重新输入")
	}
	if finduser.ID == 0 {
		return nil, fmt.Errorf("该用户未存在,请前去注册")
	}
	if finduser.Password != in.Password {
		return nil, fmt.Errorf("密码错误,请重新输入")
	}
	return &huiyunrpc.LoginResponse{
		Id: int64(finduser.ID),
	}, nil
}
